
var ns, PrdID = 0, toast, actionsheet, UIAlbumBrowser;
var app = new Vue({
    el: '#app',
    data: {
        form: {
            ID: 0,
            ProductName: '',
            SortOrder: 0,
            Title: '',
            CoverImg: '',
            Type: 1,//1-单一商品类型，2-多种商品类型
            TypeTitle: '单一商品',
            VariantLists: [
                { ID: 1, ImgPath: '', ImgPathType: '1', VariantName: '', SalePrice: '', VariantBasicPrice: '', Weight: '', WeightType: 'kg', Stock: '', SafeStock: '' } // 名称 销售单价 成本价 重量 当前库存 安全库存
            ],
        },
        // 多规格商品切换重量单位
        VariantWeightCurrent: 0,
        // 商品详情图列表
        imglist: [],
        imgindex: 0,
        select_imglist: [],
        select_imgindex: 0,
        maxuploadcount: 0,
        item: 0,//1上传一张图片
        showAll: true,
        select_weight: false,
        selectedUnit: 'g',//单位
        Category: {
            show: false,
            loading: false,
            init: false,
            list: [],
            oldList: [],
            current: {},
        },
        baseUri: CONFIG.url,
    },
    created() {
        ns = window.Foresight.Util
    },
    methods: {
        // 编辑 拉取商品详情
        handPullPrdInfo: function () {
            var that = this
            const params = {
                action: "getproductdetail",
                ProductID: PrdID
            }
            ns.post(params, function (succeed, data, err) {
                if (succeed) {
                    console.log(JSON.stringify(data))
                    const ProductInfo = data.ProductInfo || {}
                    const product = ProductInfo.Product || {}
                    const backImg = ProductInfo.BackImg || []
                    if (backImg.length > 0) {
                        that.imglist = backImg.map(b => {
                            return { ID: b.ID, url: b.IconPicPath, name: b.IconPicPath }
                        })
                    }
                    if (product.CoverImage !== '') {
                        that.form.CoverImg = product.CoverImage
                    }
                    const variants = [{
                        ID: 1,
                        ImgPath: product.CoverImage || '',
                        ImgPathType: "2",
                        VariantName: product.TypeTitle || '',
                        SalePrice: product.SalePrice || '',
                        VariantBasicPrice: product.BasicPrice || '',
                        Weight:(product.Weight> 0? product.Weight/1000 : 0) || '',
                        WeightType: 'kg',
                        Stock: product.Stock || '',
                        SafeStock: product.SafeStock || '',
                    }]
                    that.Category.current = {
                        ID: product.CategoryID,
                        showText: product.CategoryName,
                        text: product.CategoryName,
                        Name: product.CategoryName,
                    }
                    console.log(product.ProductName)
                    that.form.ProductName = product.ProductName || ''
                    that.form.SortOrder = product.SortOrder || ''
                    that.form.Title = product.Title || ''
                    that.form.Type = product.Type || ''
                    that.form.TypeTitle = product.TypeTitle || ''
                    that.form.VariantLists = variants
                    setContentEditorContent(product.Description || "")
                    console.log(JSON.stringify(that.form))
                } else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
        },
        // 打开选择商品分类
        handOpenCategoryPop: function () {
            const that = this
            that.Category.show = true
            if (!that.init) {
                that.Category.loading = true
                const params = {
                    action: "getsearcherproductlistparams",
                }
                ns.post(params, function (succeed, data, err) {
                    console.log(JSON.stringify(data));
                    if (succeed) {
                        that.Category.init = true
                        that.Category.loading = false
                        const List = data.CategoryList || [];
                        that.Category.oldList = JSON.parse(JSON.stringify(List))
                        const treeList = that.buildTree(List, 0, "ID", 'ParentID')
                        const showTreeList = []
                        treeList.map(c => {
                            const cs = {
                                ID: c.ID,
                                showText: c.Name,
                                text: c.Name,
                                Name: c.Name,
                            }
                            showTreeList.push(cs)
                            // console.log(JSON.stringify(c.children));
                            if (c.children!=undefined&&c.children.length > 0) {
                                c.children.map(cc => {
                                    const ccs = {
                                        ID: c.ID,
                                        showText: "----" + cc.Name,
                                        text: c.Name + "-" + cc.Name,
                                        Name: cc.Name,
                                    }
                                    showTreeList.push(ccs)
                                })
                            }
                        })
                        that.Category.list = showTreeList
                    } else {
                        api.toast({
                            msg: err,
                            duration: 2000,
                            location: 'bottom'
                        });
                    }
                });
            }
        },
        // 关闭商品分类选择
        handCloseCategoryPop() {
            this.Category.show = false
        },
        // 确认选择商品分类
        handCategoryConfirm(e) {
            const currentName = e.Name
            const current = this.Category.oldList.find(res => res.Name == currentName)
            if (current !== undefined) {
                this.pro_fenlei = e.text
                this.Category.current = current
            }
            this.handCloseCategoryPop()
        },
        //处理树
        buildTree:function(arr, root, key, pKey) {
            var that=this;
            const temp = [];
            for (const item of arr) {
                if (Number(item[pKey]) === Number(root)) {
                    const children = that.buildTree(arr, item[key], key, pKey);
                    if (children.length > 0) item.children = children
                    temp.push(item);
                }
            }
            return temp;
        },

        





        // 切换商品类型
        do_select_type(e) {
            this.form.Type = e;
            if (Number(e) === 1) this.form.TypeTitle = "单一类型"
        },
        // 打开多规格重量单位选择
        handOpenVariantWeightType(ID) {
            this.VariantWeightCurrent = ID
        },
        //选择重量单位
        handToggleVariantWeightType(index, type) {
            this.form.VariantLists[index].WeightType = type
        },
        //选择图片
        choose_picture: function (num) {
            var that = this;
            that.maxuploadcount = num;
            that.item = num;
            if (num == 1) {
                ns.confirmPer('camera', function () {
                    that.choose_onepicture_start(num);
                })
            } else {
                ns.confirmPer('camera', function () {
                    that.choose_picture_start();
                })
            }
        },
        // 删除封面图
        remove_pic: function () {
            var that = this;
            that.form.CoverImg = '';
        },
        //选择单张 - 商品封面图
        choose_onepicture_start: function (num) {
            var that = this;
            UIAlbumBrowser.imagePicker({
                max: num,
                styles: {
                    bg: '#000000',
                    mark: {
                        position: 'top_right',
                        size: 20
                    },
                    nav: {
                        bg: '#000000',
                        cancelColor: '#fff',
                        cancelSize: 16,
                        nextStepColor: '#7fff00',
                        nextStepSize: 16
                    },
                    thumbnail: { //（可选项）返回的缩略图配置，**建议本图片不要设置过大** 若已有缩略图，则使用已有的缩略图。若要重新生成缩略图，可先调用清除缓存接口api.clearCache()。
                        w: 100, //（可选项）数字类型；返回的缩略图的宽；默认：原图的宽度
                        h: 100 //（可选项）数字类型；返回的缩略图的宽；默认：原图的高度
                    }
                },
                animation: true,
            }, function (ret) {
                if (ret.eventType == 'nextStep') {
                    if (ret.list && ret.list.length > 0) {
                        that.select_imglist = ret.list;
                        that.select_imgindex = 0;
                        that.UIAlbumBrowser_transPathone();
                    }
                    UIAlbumBrowser.closePicker();
                }
            });
        },
        // 切换多规格商品图片上传方式
        ImgPathTypeChange(index) {
            this.form.VariantLists[index].ImgPath = ""
        },
        //选择单张 - 商品型号图片上传
        handUploadVariantPic(index) {
            var that = this;
            UIAlbumBrowser.imagePicker({
                max: 1,
                styles: {
                    bg: '#000000',
                    mark: {
                        position: 'top_right',
                        size: 20
                    },
                    nav: {
                        bg: '#000000',
                        cancelColor: '#fff',
                        cancelSize: 16,
                        nextStepColor: '#7fff00',
                        nextStepSize: 16
                    },
                    thumbnail: { //（可选项）返回的缩略图配置，**建议本图片不要设置过大** 若已有缩略图，则使用已有的缩略图。若要重新生成缩略图，可先调用清除缓存接口api.clearCache()。
                        w: 100, //（可选项）数字类型；返回的缩略图的宽；默认：原图的宽度
                        h: 100 //（可选项）数字类型；返回的缩略图的宽；默认：原图的高度
                    }
                },
                animation: true,
            }, function (ret) {
                if (ret.eventType == 'nextStep') {
                    if (ret.list && ret.list.length > 0) {
                        const list = ret.list[0].path;
                        UIAlbumBrowser.transPath({
                            path: list
                        }, function (ret, err) {
                            if (ret) {
                                const list = ret.path;
                                // 多规格图片上传
                                const params = {
                                    action: "uploadfileone",
                                }
                                ns.post(params, function (succeed, data, err) {
                                    if (succeed) {
                                        const f = data.file || {}
                                        that.form.VariantLists[index].ImgPath = f.Path || ""
                                    }
                                }, {
                                    files: {
                                        file: [list]
                                    }
                                })
                            }
                        });
                    }
                    UIAlbumBrowser.closePicker();
                }
            });
        },
        // 删除封面图
        remove_pic_v: function (e) {
            var that = this;
            that.form.VariantLists = that.form.VariantLists.map(res => {
                if (Number(res.ID) === Number(e)) res.ImgPath = ""
                return res
            })
        },
        // 图片预览
        do_openimages_v: function (e) {
            var imageUrls = [];
            imageUrls.push(e);
            var imageBrowser = api.require('imageBrowser');
            imageBrowser.openImages({
                showList: false,
                imageUrls: imageUrls
            });
        },
        // 转换Ios图片
        UIAlbumBrowser_transPathone: function () {
            var that = this;
            var item = that.select_imglist[that.select_imgindex];
            UIAlbumBrowser.transPath({
                path: item.path
            }, function (ret, err) {
                if (ret) {
                    that.select_imgindex++;
                    if (that.select_imgindex < that.select_imglist.length) {
                        that.UIAlbumBrowser_transPathone();
                    } else {
                        that.select_imgindex = 0;
                    }
                    that.form.CoverImg = ret.path;
                }
            });
        },
        // 图片预览
        do_openimages: function () {
            var that = this;
            var imageUrls = [];
            imageUrls.push(that.ImagePath);
            var imageBrowser = api.require('imageBrowser');
            imageBrowser.openImages({
                showList: false,
                imageUrls: imageUrls
            });
        },
        //选择多张-商品详情图
        choose_picture_start: function () {
            var that = this;
            if (that.imglist.length >= that.maxuploadcount) {
                api.toast({
                    msg: '最多支持' + that.maxuploadcount + '张图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            UIAlbumBrowser.imagePicker({
                max: that.maxuploadcount - that.imglist.length,
                styles: {
                    bg: '#000000',
                    mark: {
                        position: 'top_right',
                        size: 20
                    },
                    nav: {
                        bg: '#000000',
                        cancelColor: '#fff',
                        cancelSize: 16,
                        nextStepColor: '#7fff00',
                        nextStepSize: 16
                    },
                    thumbnail: { //（可选项）返回的缩略图配置，**建议本图片不要设置过大** 若已有缩略图，则使用已有的缩略图。若要重新生成缩略图，可先调用清除缓存接口api.clearCache()。
                        w: 100, //（可选项）数字类型；返回的缩略图的宽；默认：原图的宽度
                        h: 100 //（可选项）数字类型；返回的缩略图的宽；默认：原图的高度
                    }
                },
                animation: true,
            }, function (ret) {
                if (ret.eventType == 'nextStep') {
                    if (ret.list && ret.list.length > 0) {
                        that.select_imglist = ret.list;
                        that.select_imgindex = 0;
                        that.UIAlbumBrowser_transPath();
                    }
                    UIAlbumBrowser.closePicker();
                }
                if (ret.originalPath && ret.originalPath.length > 0) {
                    that.imglist.push({
                        index: that.imgindex,
                        url: ret.originalPath,
                        thumbPath: ret.originalPath
                    });
                    that.imgindex++;
                }
            });
            return;
        },
        UIAlbumBrowser_transPath: function () {
            var that = this;
            var item = that.select_imglist[that.select_imgindex];
            UIAlbumBrowser.transPath({
                path: item.path
            }, function (ret, err) {
                if (ret) {
                    that.select_imgindex++;
                    if (that.select_imgindex < that.select_imglist.length) {
                        that.UIAlbumBrowser_transPath();
                    } else {
                        that.select_imgindex = 0;
                    }
                    that.imglist.push({
                        index: that.imgindex,
                        url: ret.path,
                        thumbPath: item.thumbPath
                    });
                    that.imgindex++;
                }
            });
        },
        remove_img: function (index) {
            var that = this;
            for (var i = 0; i < that.imglist.length; i++) {
                var item = that.imglist[i];
                if (item.index == index) {
                    that.imglist.splice(i, 1);
                }
            }

        },
        // 查看商品详情图
        do_viewimages: function (activeIndex) {
            var that = this;
            var imageUrls = [];
            for (var i = 0; i < that.imglist.length; i++) {
                imageUrls.push(that.imglist[i].url);
            }
            var imageBrowser = api.require('imageBrowser');
            imageBrowser.openImages({
                showList: false,
                activeIndex: activeIndex,
                imageUrls: imageUrls
            });
        },
        // 重量单位切换
        WeightTypeChange4Type1(e) {
            this.form.VariantLists[0].WeightType = e
            this.select_weight = false
        },
        // 型号切换
        typeChange(e) {
            if (Number(e) === 1) {
                this.add.form.VariantLists = [{ ID: 1, ImgPath: '', ImgPathType: '1', VariantName: '', SalePrice: '', VariantBasicPrice: '', Weight: '', WeightType: 'kg', Stock: '', SafeStock: '' }] // 名称 销售单价 成本价 重量 当前库存 安全库存]
            } else {
                this.add.form.VariantLists = []
            }
        },
        // 新增商品类型
        handAddNewVariant() {
            const addInfo = { ID: this.form.VariantLists.length + 1, ImgPath: '', ImgPathType: '1', VariantName: '', SalePrice: '', VariantBasicPrice: '', Weight: '', WeightType: 'kg', Stock: '', SafeStock: '' }
            this.form.VariantLists.push(addInfo)
        },
        // 删除商品类型
        handDelVariant(e) {
            if (Number(e) === 0) return
            this.form.VariantLists = this.form.VariantLists.filter(res => Number(res.ID) !== Number(e))
        },
        // 重量转换
        toggleWeight2g(num, unit = 'kg') {
            const u = unit.toLowerCase()
            if (u === 'g') return num
            if (u === 'kg') return num * 1000
            if (u === 't') return num * 1000 * 1000
        },
        // 提交商品
        handConfirmAdd() {
            const content = contentEditor.getContent()
            const params = {}
            const { CategoryID, ProductName, SortOrder, Title, CoverImg, Type, TypeTitle, VariantLists } = this.form
            if (CoverImg === "") {
                return api.toast({
                    msg: `请上传商品封面图片`,
                    duration: 2000,
                    location: 'bottom'
                });
            }
            const Category = this.Category.current
            params.ID = PrdID
            params.CategoryID = Category.ID
            params.CategoryName = Category.Name
            params.ProductName = ProductName
            params.SortOrder = SortOrder
            params.Title = Title
            params.CoverImg = CoverImg
            params.BackImg = JSON.stringify(this.imglist.map(res => res.url))
            params.Type = Type
            params.TypeTitle = TypeTitle
            if (Number(Type) === 2 && VariantLists.length <= 0) {
                return this.$message({
                    showClose: true,
                    message: `商品有多种型号的时候,必须填写至少一项规格`,
                    type: 'error',
                    onClose: () => {
                        this.add.loading = false
                    },
                });
            }
            // 检测数据
            VariantLists.forEach(v => {
                if (Number(Type) === 2 && Number(v.ImgPathType) === 1 && v.imgPath === '') {
                    return api.toast({
                        msg: '手动上传图片的情况下,图片必传',
                        duration: 2000,
                        location: 'bottom'
                    });
                }
                if (Number(Type) === 2 && v.VariantName == '') {
                    return api.toast({
                        msg: '请填写型号名称',
                        duration: 2000,
                        location: 'bottom'
                    });
                }
                if (v.SalePrice == '') {
                    return api.toast({
                        msg: '请填写销售单价',
                        duration: 2000,
                        location: 'bottom'
                    });
                }
                if (v.VariantBasicPrice == '') {
                    return api.toast({
                        msg: '请填写成本单价',
                        duration: 2000,
                        location: 'bottom'
                    });
                }
                if (v.Weight == '') {
                    return api.toast({
                        msg: '请填写重量',
                        duration: 2000,
                        location: 'bottom'
                    });
                }
                if (v.Stock == '') {
                    return api.toast({
                        msg: '请填写当前库存',
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
            params.VariantLists = JSON.stringify(VariantLists.map(v => {
                const vr = {
                    ImgPath: Number(v.ImgPathType) === 2 ? "" : (v.ImgPath || ''),
                    VariantName: v.VariantName,
                    SalePrice: Number(v.SalePrice),
                    VariantBasicPrice: Number(v.VariantBasicPrice),
                    Weight: this.toggleWeight2g(v.Weight, v.WeightType),
                    Stock: v.Stock,
                    SafeStock: v.SafeStock > 0 ? v.SafeStock : 0,
                }
                return vr
            }))
            params.Description = content
            params.action = "savebusinessproduct"
            const imgPath = {
                CoverImg: CoverImg,
                BackImg: this.imglist.map(res => res.url)
            }
            console.log(JSON.stringify(params))
            console.log(JSON.stringify(imgPath))
            ns.post(params, function (succeed, data, err) {
                if (succeed) {
                    api.toast({
                        msg: '商品添加成功',
                        duration: 2000,
                        location: 'bottom'
                    });
                    api.sendEvent({
                        name:'reloadlist'
                    });
                    setTimeout(() => {
                        api.closeWin();
                    }, 400);
                } else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                files: imgPath
            });
        },
    }
});
var contentEditor = new Eleditor({
    // 编辑区域dom对象
    el: '#contentEditor',
    // 图片上传自定义方法
    // uploader: function () {
    //     return new Promise(function (_resolve, _reject) {
    //         openPhoto('pic', _resolve, _reject);
    //     })
    // },
    uploader: function () {
        return new Promise(function (_resolve, _reject) {
            openPhoto('pic', function (ret) {
                console.log(JSON.stringify(ret));
                contentEditor.saveState();
                contentEditor.getEditNode().after(`
                            <img src="${ret}" />
                    `);
                contentEditor.hideEditorControllerLayer();
            }, function (err) {
                alert(err)
            });
        })
    },
    /*初始化完成钩子*/
    mounted: function () {

    },
    /*文档内容变化*/
    changer: function () {
    },
    /*自定义按钮的例子*/
    toolbars: [
        'insertText',
        'editText',
        'insertImage',
        // {
        //     id: 'insertImage',
        //     name: '插图片',
        //     handle: function (select, controll) {
        //         openPhoto('pic', function (ret) {
        //             console.log(JSON.stringify(ret));
        //             contentEditor.saveState();
        //             contentEditor.getEditNode().after(`
        //                         <img src="${ret}" />
        //                 `);
        //             contentEditor.hideEditorControllerLayer();
        //         }, function (err) {
        //             alert(err)
        //         });
        //         return false;
        //     }
        // },
        'insertLink',
        'insertHr',
        'delete',
        //自定义一个视频按钮
        {
            id: 'insertVideo',
            name: '插入视频',
            handle: function (select, controll) {//回调返回选择的dom对象和控制按钮对象
                openPhoto('video', function (ret) {
                    contentEditor.saveState();
                    contentEditor.getEditNode().after(`
							<div class='Eleditor-video-area'>
								<video src="${ret}" autoplay="autoplay" controls="controls"></video>
							</div>
						`);
                    contentEditor.hideEditorControllerLayer();
                }, function (err) {
                    alert(err)
                });
                return false;
            }
        },
        'undo',
        'cancel'
    ],
    placeHolder: '编辑商品详情'
});
apiready = () => {
    api.parseTapmode();
    ns = window.Foresight.Util;
    toast = new auiToast();
    actionsheet = new auiActionsheet();
    UIAlbumBrowser = api.require('UIAlbumBrowser');
    PrdID = api.pageParam.ID || 0;
    if(PrdID > 0 ){
        app.handPullPrdInfo()
    }
};
function test() {
    contentEditor.saveState();
    contentEditor.getEditNode().after($('<p>1111</p>'));
    contentEditor.hideEditorControllerLayer();
}
// 给编辑器写入文件
function setContentEditorContent(e) {
    setTimeout(() => {
        contentEditor.append(e);
    }, 1000)
}

function openPhoto(type, _resolve, _reject) {
    console.log('111111111111111111');
    api.actionSheet({
        title: '选择图片',
        cancelTitle: '关闭',
        buttons: ['打开相机', '本地图库'],
        style: {
            fontNormalColor: '#777777',
            fontPressColor: '#e03b6c'
        }
    }, function (ret, err) {
        console.log(JSON.stringify(ret));
        if(ret.buttonIndex==3){
            return;
        }
        api.getPicture({
            sourceType: ret.buttonIndex == 1 ? 'camera' : 'library',
            encodingType: "jpg",
            mediaValue: type, // pic video
            quality: 100,
            destinationType: 'url', //url  base64
            targetWidth: 768,
            targetHeight: 768,
            saveToPhotoAlbum: false,
            allowEdit: false
        }, function (ret, err) {
            if (ret && ret.data) {
                var options = {};
                options.action = "uploadfileone";
                var filelist = [];
                filelist.push(ret.data);
                ns.post(options, function(succeed, data, err) {
                    console.log(JSON.stringify(data));
                    if (succeed) {
                        if(data.file.FullPath==null||data.file.FullPath==undefined||data.file.FullPath==''){
                            _reject('上传服务器失败!');
                            return;
                        }
                        let retimg=data.file;
                        _resolve(retimg.FullPath);
                    } else if (err) {
                        _reject(err);
                    }
                }, {
                    toast: true,
                    files: {
                        file: filelist
                    }
                }); 
            } else {
                _reject('上传失败!');
            }
        });
    })

}
